package com.jinmingwu.musicplay.myApplication;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.jinmingwu.musicplay.R;
import com.jinmingwu.musicplay.data.Music;
import com.jinmingwu.musicplay.data.MusicList;
import com.jinmingwu.musicplay.model.PropertyBean;
import com.jinmingwu.musicplay.utils.PermissionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private boolean firstPlay = true;
    private ImageButton imgBtn_Previous;
    private ImageButton imgBtn_PlayOrPause;
    private ImageButton imgBtn_Stop;
    private ImageButton imgBtn_Next;
    private ListView list;
    private RelativeLayout root_Layout;
    private SeekBar seekBar;
    private Handler seekBarHandler;

    private TextView text_Current;
    private TextView text_Duration;
    private TextView textView;

    private ArrayList<Music> mainMusicList;
    //歌曲序号，下标从0开始
    private int number = 0;

    //播放状态
    private int status;

    //绑定广播接收器，可以接收广播
    private StatusChangedReceiver receiver;

    //歌曲的持续时间和当前位置，用作进度条
    private int duration;
    private int time;

    //进度条控制常量
    private static final int PROGRESS_INCREASE = 0;
    private static final int PROGRESS_PAUSE = 1;
    private static final int PROGRESS_RESET = 2;
    private Menu menu;

    // 播放模式常量
    private static final int MODE_LIST_SEQUENCE = 0; //顺序播放
    private static final int MODE_SINGLE_CYCLE = 1; //单曲循环
    private static final int MODE_LIST_CYCLE = 2; //列表循环
    private static final int MODE_RANDOM_PLAY = 3; //随机播放
    private int playMode; //播放模式

    // 退出判断标记
    private static boolean isExit = false;

    // 音量控制
    private TextView tv_vol;
    private SeekBar seekBar_val;

    // 睡眠模式相关组件，标识常量
    private ImageView imageViewSleep;
    private Timer timerSleep;
    private static final boolean NOTSLEEP = false;
    private static final boolean ISSLEEP = true;
    // 默认睡眠时间
    private int sleepminute = 20;
    // 标记是否打开睡眠模式
    private static boolean sleepMode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mainMusicList = MusicList.getMusicList();
        //player = new MediaPlayer();

        findViews();
        registerListeners();
        PermissionUtils.checkExternalStoragePermission(this);

        duration = 0;
        time = 0;

        //绑定广播接收器，可以接收广播
        bindStatusChangedReceiver();
        initSeekBarHandler();
        startService(new Intent(this, MusicService.class));
        status = MusicService.COMMAND_STOP;

        // 默认播放顺序：顺序播放
        playMode = MainActivity.MODE_LIST_SEQUENCE;

        // 默认睡眠状态为关闭状态
        sleepMode = MainActivity.NOTSLEEP;
    }

    @Override
    protected void onResume() {
        super.onResume();
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);

        //保存activity设置的主题
        PropertyBean property = new PropertyBean(MainActivity.this);
        String theme = property.getTheme();
        setTheme(theme);

        if (PermissionUtils.checkExternalStoragePermission(this)) {
            initMusicList();
            initListView();
            checkMusicFile();
        } else {
            Toast.makeText(this, R.string.jurisdiction, Toast.LENGTH_LONG);
        }

        audio_Control();

        // 睡眠模式打开时显示图标，关闭时隐藏
        if (sleepMode == MainActivity.ISSLEEP) {
            imageViewSleep.setVisibility(View.VISIBLE);
        } else {
            imageViewSleep.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        if (status == MusicService.STATUS_STOPPED) {
            stopService(new Intent(this, MusicService.class));
        }
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int progress;
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                exitByDoubleClick();
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                progress = seekBar_val.getProgress();
                if (progress != 0) {
                    seekBar_val.setProgress(progress - 1);
                }
                return true;
            case KeyEvent.KEYCODE_VOLUME_UP:
                progress = seekBar_val.getProgress();
                if (progress != seekBar_val.getMax()) {
                    seekBar_val.setProgress(progress + 1);
                }
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //组件绑定id
    private void findViews() {
        imgBtn_Previous = (ImageButton) findViewById(R.id.imageButton1);
        imgBtn_PlayOrPause = (ImageButton) findViewById(R.id.imageButton2);
        imgBtn_Stop = (ImageButton) findViewById(R.id.imageButton3);
        imgBtn_Next = (ImageButton) findViewById(R.id.imageButton4);
        list = (ListView) findViewById(R.id.listView1);
        root_Layout = (RelativeLayout) findViewById(R.id.relativeLayout1);
        seekBar = (SeekBar) findViewById(R.id.seekBar1);
        text_Current = (TextView) findViewById(R.id.textView1);
        text_Duration = (TextView) findViewById(R.id.textView2);
        textView = (TextView) findViewById(R.id.textView);
        tv_vol = (TextView) findViewById(R.id.main_tv_volumeText);
        seekBar_val = (SeekBar) findViewById(R.id.main_sb_volumebar);
        imageViewSleep = (ImageView) findViewById(R.id.main_iv_sleep);
    }

    //组件绑定监听器
    private void registerListeners() {
        imgBtn_Previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (playMode) {
                    case MainActivity.MODE_LIST_CYCLE:
                        sendBroadcastOnCommand(MusicService.COMMAND_LIST_CYCLE_UP);
                        break;
                    case MainActivity.MODE_RANDOM_PLAY:
                        sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
                        break;
                    default:
                        sendBroadcastOnCommand(MusicService.COMMAND_PREVIOUS);
                        break;
                }
            }
        });

        imgBtn_PlayOrPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (status) {
                    case MusicService.STATUS_PLAYING:
                        sendBroadcastOnCommand(MusicService.COMMAND_PAUSE);
                        break;
                    case MusicService.STATUS_PAUSED:
                        sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        break;
                    case MusicService.COMMAND_STOP:
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        break;
                    default:
                        break;
                }
            }
        });

        imgBtn_Stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcastOnCommand(MusicService.COMMAND_STOP);
            }
        });

        imgBtn_Next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (playMode) {
                    case MainActivity.MODE_LIST_CYCLE:
                        sendBroadcastOnCommand(MusicService.COMMAND_LIST_CYCLE_DOWN);
                        break;
                    case MainActivity.MODE_RANDOM_PLAY:
                        sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
                        break;
                    default:
                        sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                        break;
                }
            }
        });

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                number = position;
                firstPlay = false;
                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //进度条暂停移动
                seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (status != MusicService.STATUS_STOPPED) {
                    time = seekBar.getProgress();
                    //更新文本
                    text_Current.setText(formatTime(time));
                    //发送广播给MusicService执行跳转
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                }
                if (status == MusicService.STATUS_PLAYING) {
                    //发送广播给MusicService执行跳转
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    //进度条恢复移动
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 100);
                }
                if (status == MusicService.STATUS_PAUSED) {
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                }
            }
        });
    }

    //初始化音乐列表
    private void initMusicList() {
        //避免重复添加音乐
        if (mainMusicList.isEmpty()) {
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[]{
                            MediaStore.Audio.Media.TITLE,
                            MediaStore.Audio.Media.DURATION,
                            MediaStore.Audio.Media.ALBUM,
                            MediaStore.Audio.Media.ARTIST,
                            MediaStore.Audio.Media._ID,
                            MediaStore.Audio.Media.DATA,
                            MediaStore.Audio.Media.DISPLAY_NAME
                    }, null, null,
                    MediaStore.Audio.AudioColumns.TITLE
            );

            if (mMusicCursor != null) {
                int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
                int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
                int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
                int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
                int indexAlbum = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ALBUM);

                for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor.moveToNext()) {
                    String mTitle = mMusicCursor.getString(indexTitle);
                    String mArtist = mMusicCursor.getString(indexArtist);
                    String mTotalTime = mMusicCursor.getString(indexTotalTime);
                    String mPath = mMusicCursor.getString(indexPath);
                    String mAlbum = mMusicCursor.getString(indexAlbum);

                    if (mArtist.equals("<unknown>")) {
                        mArtist = "未知歌手";
                    }

                    if (mAlbum.equals("<unknown>")) {
                        mAlbum = "未知专辑";
                    }

                    Music music = new Music(++number, mTitle, mArtist, mPath, mTotalTime, mAlbum);
                    mainMusicList.add(music);
                }
            }
        }
    }

    //设置适配器并初始化listView
    private void initListView() {
        List<Map<String, String>> list_map = new ArrayList<>();
        Map<String, String> map;
        SimpleAdapter simpleAdapter;
        for (Music music : mainMusicList) {
            map = new HashMap<>();
            map.put("id", String.valueOf(music.getId()));
            map.put("title", music.getName());
            map.put("artist", music.getArtist() + " - " + music.getAlbum());
            list_map.add(map);
        }

        String[] from = new String[]{"id", "title", "artist"};
        int[] to = {R.id.listview_tv_id, R.id.listview_tv_title_item, R.id.listview_tv_artist_item};
        simpleAdapter = new SimpleAdapter(this, list_map, R.layout.listview, from, to);
        list.setAdapter(simpleAdapter);
    }

    //列表中没有歌曲，则设置按钮不可用，并提醒用户
    private void checkMusicFile() {
        if (mainMusicList.isEmpty()) {
            imgBtn_Next.setEnabled(false);
            imgBtn_Stop.setEnabled(false);
            imgBtn_PlayOrPause.setEnabled(false);
            imgBtn_Previous.setEnabled(false);
            Toast.makeText(getApplicationContext(), "当前没有歌曲文件", Toast.LENGTH_SHORT).show();
        } else {
            imgBtn_Previous.setEnabled(true);
            imgBtn_Stop.setEnabled(true);
            imgBtn_PlayOrPause.setEnabled(true);
            imgBtn_Next.setEnabled(true);
        }
    }

    //绑定广播接收器
    private void bindStatusChangedReceiver() {
        receiver = new StatusChangedReceiver();
        IntentFilter filter = new IntentFilter(MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver, filter);
    }

    //发送命令，控制音乐播放
    private void sendBroadcastOnCommand(int command) {
        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);

        //根据不同指令传输不同数据
        switch (command) {
            case MusicService.COMMAND_PLAY:
                if (firstPlay) {
                    intent.putExtra("number", 1);
                } else {
                    intent.putExtra("number", number);
                }
                break;
            case MusicService.COMMAND_SEEK_TO:
                intent.putExtra("time", time);
                break;
            case MusicService.COMMAND_PREVIOUS:
            case MusicService.COMMAND_NEXT:
            case MusicService.COMMAND_PAUSE:
            case MusicService.COMMAND_STOP:
            case MusicService.COMMAND_RESUME:
            case MusicService.COMMAND_RANDOM:
            default:
                break;
        }
        sendBroadcast(intent);
    }

    //接收播放器状态更新的广播
    class StatusChangedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            number = intent.getIntExtra("number", number);
            //获取播放器状态
            status = intent.getIntExtra("status", -1);
            switch (status) {
                case MusicService.STATUS_PLAYING:
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
                    seekBarHandler.removeMessages(PROGRESS_INCREASE);
                    time = intent.getIntExtra("time", 0);
                    duration = intent.getIntExtra("duration", 0);
                    list.setSelection(number);
                    seekBar.setProgress(time);
                    seekBar.setMax(duration);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000L);
                    text_Duration.setText(formatTime(duration));
                    MainActivity.this.setTitle("正在播放：" + mainMusicList.get(number).getName() + " - " + mainMusicList.get(number).getArtist());
                    textView.setText(mainMusicList.get(number).getName() + " - " + mainMusicList.get(number).getArtist());
                    break;
                case MusicService.STATUS_STOPPED:
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
                    time = 0;
                    duration = 0;
                    text_Duration.setText(formatTime(time));
                    text_Current.setText(formatTime(time));
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle(R.string.app_name);
                    textView.setText("");
                    break;
                case MusicService.STATUS_PAUSED:
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
                    seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
                    MainActivity.this.setTitle(mainMusicList.get(number).getName() + " - " + mainMusicList.get(number).getArtist());
                    break;
                case MusicService.STATUS_COMPLETED:
                    number = intent.getIntExtra("number", 0);
                    switch (playMode) {
                        case MODE_LIST_SEQUENCE:
                            // 顺序播放
                            if (number == MusicList.getMusicList().size() - 1) {
                                sendBroadcastOnCommand(MusicService.STATUS_STOPPED);
                            } else {
                                sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                            }
                            break;
                        case MODE_SINGLE_CYCLE:
                            // 单曲循环
                            sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                            break;
                        case MODE_LIST_CYCLE:
                            // 列表循环
                            if (number == MusicList.getMusicList().size() - 1) {
                                number = 0;
                                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                            } else {
                                sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                            }
                            break;
                        case MODE_RANDOM_PLAY:
                            // 随机播放
                            sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
                            break;
                        default:
                            break;
                    }
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle(R.string.app_name);
                    break;
                default:
                    break;
            }
        }
    }

    //设置Activity的主题
    private void setTheme(String theme) {
        if ("彩色".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_color);
        } else if ("花朵".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_digit_flower);
        } else if ("群山".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_mountain);
        } else if ("小狗".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_running_dog);
        } else if ("冰雪".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_snow);
        } else if ("女孩".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_music_girl);
        } else if ("朦胧".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_blur);
        }
    }

    //创建菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    //处理菜单点击事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_theme:
                new AlertDialog.Builder(this).setTitle("请选择主题")
                        .setItems(R.array.theme, new android.content.DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String[] str = getApplication().getResources().getStringArray(R.array.theme);
                                String theme = str[which];
                                MainActivity.this.setTheme(theme);
                                PropertyBean property = new PropertyBean(MainActivity.this);
                                property.setAndSaveTheme(theme);
                            }
                        }).show();
                break;
            case R.id.menu_playmode:
                String[] mode = new String[]{"顺序播放", "单曲循环", "列表循环", "随机播放"};
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle(R.string.playMode);
                builder.setSingleChoiceItems(mode, playMode,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                playMode = which;
                            }
                        });
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                playMode = MainActivity.MODE_LIST_SEQUENCE;
                                Toast.makeText(getApplicationContext(), R.string.sequencePlay, Toast.LENGTH_SHORT).show();
                                break;
                            case 1:
                                playMode = MainActivity.MODE_SINGLE_CYCLE;
                                Toast.makeText(getApplicationContext(), R.string.circulationPlay, Toast.LENGTH_SHORT).show();
                                break;
                            case 2:
                                playMode = MainActivity.MODE_LIST_CYCLE;
                                Toast.makeText(getApplicationContext(), R.string.listLoopPlay, Toast.LENGTH_SHORT).show();
                                break;
                            case 3:
                                playMode = MainActivity.MODE_RANDOM_PLAY;
                                Toast.makeText(getApplicationContext(), R.string.randomPlay, Toast.LENGTH_SHORT).show();
                                break;
                            default:
                                break;
                        }
                    }
                });
                builder.create().show();
                break;
            case R.id.menu_about:
                new AlertDialog.Builder(MainActivity.this).setTitle("MusicPlay")
                        .setMessage(R.string.about2).show();
                break;
            case R.id.menu_quit:
                //退出程序
                new AlertDialog.Builder(this).setTitle(R.string.quit)
                        .setMessage(R.string.quit_message)
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                System.exit(0);
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
                break;
            case R.id.menu_sleep:
                showSleepDialog();
                break;
            case R.id.menu_lrc:
                // 显示歌词
                Toast.makeText(getApplicationContext(), "敬请期待", Toast.LENGTH_SHORT).show();
//                Intent intentLrc = new Intent(MainActivity.this, LrcActivity.class);
//                startActivity(intentLrc);
                break;
            default:
                break;
        }
        return true;
    }

    private String formatTime(int time) {
        int minute = time / 1000 / 60;
        int second = time / 1000 % 60;
        String minuteString;
        String secondString;
        if (minute < 10) {
            minuteString = "0" + minute;
        } else {
            minuteString = "" + minute;
        }
        if (second < 10) {
            secondString = "0" + second;
        } else {
            secondString = "" + second;
        }
        return minuteString + ":" + secondString;
    }

    private void initSeekBarHandler() {
        seekBarHandler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case PROGRESS_INCREASE:
                        if (seekBar.getProgress() < duration) {
                            //进度条前进一秒
                            seekBar.setProgress(time);
//                            seekBar.incrementProgressBy(1000);
                            seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            //修改显示当前进度的文本
                            text_Current.setText(formatTime(time));
                            time += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        //重置进度条画面
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(0);
                        text_Current.setText("00:00");
                        break;
                }
            }
        };
    }

    // 判断两次点击退出应用
    private void exitByDoubleClick() {
        Timer timer = null;
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), R.string.quit_click, Toast.LENGTH_SHORT).show();
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        } else {
            System.exit(0);
        }
    }

    // 音量调整
    private void audio_Control() {
        // 获取音量管理器
        final AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        // 设置当前调整音量大小只是针对媒体音乐
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        // 设置滑动条最大值
        final int max_progress = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        seekBar_val.setMax(max_progress);

        // 获取当前音量
        int progress = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekBar_val.setProgress(progress);
        tv_vol.setText("音量：" + (progress * 100 / max_progress) + "%");

        seekBar_val.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tv_vol.setText("音量：" + (progress * 100) / (max_progress) + "%");
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, AudioManager.FLAG_PLAY_SOUND);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    // 睡眠模式
    private void showSleepDialog() {
        // 获取布局，初始化View类对象
        final View userViewer = this.getLayoutInflater().inflate(R.layout.dialog, null);

        // 获取组件对象
        final TextView tv_minute = (TextView) userViewer.findViewById(R.id.dialog_tv);
        final Switch switchC = (Switch) userViewer.findViewById(R.id.dialog_switch);
        final SeekBar seekBar = (SeekBar) userViewer.findViewById(R.id.dialog_seekbar);

        tv_minute.setText("睡眠于：" + sleepminute + "分钟");

        // 根据睡眠状态来确认Switch状态
        if (sleepMode == MainActivity.ISSLEEP) {
            switchC.setChecked(true);
        }
        seekBar.setMax(60);
        seekBar.setProgress(sleepminute);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                sleepminute = progress;
                tv_minute.setText("睡眠于：" + sleepminute + "分钟");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        switchC.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                sleepMode = isChecked;
            }
        });

        // 定义定时器任务
        final TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.exit(0);
            }
        };

        // 定义对话框以及初始化
        final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("选择睡眠时间（0-60分钟）");
        // 设置布局
        dialog.setView(userViewer);

        // 设置取消按钮响应事件
        dialog.setNegativeButton(R.string.cannel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        // 设置重置按钮响应事件
        dialog.setNeutralButton(R.string.resetting, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (sleepMode == MainActivity.ISSLEEP) {
                    timerTask.cancel();
                    if (timerSleep != null)
                        timerSleep.cancel();
                }
                sleepMode = MainActivity.NOTSLEEP;
                sleepminute = 20;
                imageViewSleep.setVisibility(View.INVISIBLE);
            }
        });
        // 设置确定按钮响应事件
        dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (sleepMode == MainActivity.ISSLEEP) {
                    timerSleep = new Timer();
                    int time = seekBar.getProgress();

                    // 启动任务，time*60*1000毫秒后执行
                    timerSleep.schedule(timerTask, time * 60 * 1000);
                    imageViewSleep.setVisibility(View.VISIBLE);
                } else {
                    // 取消任务
                    timerTask.cancel();
                    if (timerSleep != null) {
                        timerSleep.cancel();
                    }
                    dialog.dismiss();
                    imageViewSleep.setVisibility(View.INVISIBLE);
                }
            }
        });
        dialog.show();
    }
}
